import React, {Fragment} from "react";
import {
    getAdministrativeArea, getAdministrativeAreaId, addAdministrativeArea,
    delAdministrativeArea,getSubAdministrativeAreaId, modAdministrativeArea
} from '../../../../service/api';
import { Table, Button, Form, Modal, Cascader, Row, Col, Input, message, Checkbox, Popconfirm, Tabs } from 'antd';
const FormItem = Form.Item;
const TabPane = Tabs.TabPane;

class AddAdministrativeDivision extends React.Component {

    state = {
        visible: false,
        confirmLoading: false,
        fetching: false,
        town: {}
    }

    showModal = () => {
        this.setState({
            visible: true
        });
    }

    handleCancel = () => {
        this.props.form.resetFields();
        this.props.close();
        this.setState({
            visible: false,
            confirmLoading: false
        });
    }

    handleOk = () => {
        let self = this;
        this.props.form.validateFields((err, values) => {
            if (!err) {
                self.setState({
                    confirmLoading: true,
                });
                values.parentid = self.props.id;
                values.status?values.status = 1:values.status = 0;
                console.log(values)
                addAdministrativeArea(values).then(function (data) {
                    if(data.code === 200){
                        self.setState({
                            visible: false,
                            confirmLoading: false,
                        })
                        self.props.retrieve();
                        message.success("添加成功");
                    }else{
                        message.error(data.msg);
                        self.setState({
                            confirmLoading: false
                        })
                    }
                })
            }
        })
    }

    render() {
        const {visible, confirmLoading} = this.state;
        const {getFieldDecorator} = this.props.form;
        return (
            <Fragment>
                <Button className="fl ml10 addNew formAddBtn" type="primary" style={{marginTop: 0}} onClick={this.showModal}>新增</Button>
                <Modal title="新增行政区划"
                       visible={visible}
                       maskClosable={false}
                       onOk={this.handleOk}
                       confirmLoading={confirmLoading}
                       onCancel={this.handleCancel}
                       okText="提交"
                       cancelText="取消"
                       width="80%"
                >
                    <Form className="modalForm">
                        <Row type="flex" justify="center" align="top">
                            <Col span={12}>
                                <FormItem label="地区名称">
                                    {getFieldDecorator('regionname',{
                                        initialValue: ""
                                    })(
                                        <Input placeholder="地区名称" />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={12}>
                                <FormItem label="地区代码">
                                    {getFieldDecorator('regioncode',{
                                        initialValue: ""
                                    })(
                                        <Input placeholder="地区代码" />
                                    )}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="center" align="top">
                            <Col span={12}>
                                <FormItem label="排序">
                                    {getFieldDecorator('orderby',{
                                        initialValue: ""
                                    })(
                                        <Input placeholder="排序" />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={12}>
                                <FormItem label="排序">

                                    {getFieldDecorator('status', {
                                        valuePropName: 'checked',
                                        initialValue: true,
                                    })(
                                        <Checkbox>是否可见</Checkbox>
                                    )}
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>

                </Modal>
            </Fragment>
        )
    }

}
const AddAdministrativeDivisionForm = Form.create()(AddAdministrativeDivision);

const columns = [
    {
        dataIndex: 'id',
        title: 'id',
        width: 80
    },
    {
        dataIndex: 'regionname',
        title: '地区名称',
        width: 120
    },
    {
        dataIndex: 'regioncode',
        title: '地区代码',
        width: 150
    },
    {
        dataIndex: 'plevel',
        title: '层级',
        width: 100
    },
    {
        dataIndex: 'orderby',
        title: '排序值',
        width: 100
    },
    {
        dataIndex: 'status',
        title: '状态',
        width: 100
    }

]

class ModAdministrativeDivision extends React.Component {

    state = {
        visible: false,
        confirmLoading: false,
        fetching: false,
        town: {}
    }

    showModal = () => {
        let self = this;
        self.setState({loading: true, id: this.props.id, visible: true});
        getAdministrativeAreaId(this.props.id).then(function (data) {
            if(data.code === 200){
                self.setState({data: data.data, loading: false});
            }
        })

    }

    handleCancel = () => {
        this.props.form.resetFields();
        this.setState({
            visible: false,
            confirmLoading: false
        });
    }

    handleOk = () => {
        let self = this;
        this.props.form.validateFields((err, values) => {
            if (!err) {
                self.setState({
                    confirmLoading: true,
                });
                values.parentid = self.props.parentId;
                values.status?values.status = 1:values.status = 0;
                console.log(values)
                modAdministrativeArea(this.state.id, values).then(function (data) {
                    if(data.code === 200){
                        self.setState({
                            visible: false,
                            confirmLoading: false,
                        })
                        self.props.retrieve();
                        message.success("添加成功");
                    }else{
                        message.error(data.msg);
                        self.setState({
                            confirmLoading: false
                        })
                    }
                })
            }
        })
    }

    render() {
        const {visible, confirmLoading} = this.state;
        const {getFieldDecorator} = this.props.form;
        return (
            <Fragment>
                <Button type="primary" style={{marginTop: 0}} onClick={this.showModal}>修改</Button>
                <Modal title="修改行政区划"
                       visible={visible}
                       maskClosable={false}
                       onOk={this.handleOk}
                       confirmLoading={confirmLoading}
                       onCancel={this.handleCancel}
                       okText="提交"
                       cancelText="取消"
                       width="80%"
                >
                    {this.state.data?<Form className="modalForm">
                        <Row type="flex" justify="center" align="top">
                            <Col span={12}>
                                <FormItem label="地区名称">
                                    {getFieldDecorator('regionname',{
                                        initialValue: this.state.data.regionname
                                    })(
                                        <Input placeholder="地区名称" />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={12}>
                                <FormItem label="地区代码">
                                    {getFieldDecorator('regioncode',{
                                        initialValue: this.state.data.regioncode
                                    })(
                                        <Input placeholder="地区代码" />
                                    )}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="center" align="top">
                            <Col span={12}>
                                <FormItem label="排序">
                                    {getFieldDecorator('orderby',{
                                        initialValue: this.state.data.orderby
                                    })(
                                        <Input placeholder="排序" />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={12}>
                                <FormItem label="排序">
                                    {getFieldDecorator('status', {
                                        valuePropName: 'checked',
                                        initialValue: this.state.data.status,
                                    })(
                                        <Checkbox>是否可见</Checkbox>
                                    )}
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>:true}

                </Modal>
            </Fragment>
        )
    }

}
const ModAdministrativeDivisionForm = Form.create()(ModAdministrativeDivision);

class AdministrativeDivision extends React.Component {

    state = {
        permissions: JSON.parse(localStorage.permissions),
        limit: 20,
        data: [],
        loading: true,
        regionId: "21",
        pagination: {pageSize: 20},
        height: document.body.clientHeight - 230,
    }


    componentDidMount() {
        columns.push({
            title: '操作',
            width: 150,
            render: (record) => (
                <div className="tableOperation">
                    {this.state.permissions["sys:administrativeArea:update"]?<ModAdministrativeDivisionForm parentId={this.state.regionId} retrieve={this.getData} id={record.id} />:true}
                    {this.state.permissions["sys:administrativeArea:delete"]?
                        <Popconfirm placement="leftBottom" title={`确定删除:${record.regionname}吗?`} id={record.id.toString()} onConfirm={() => this.del(record.id)} okText="确定" cancelText="取消">
                            <Button type="danger" className="ml10" id={record.userId} ghost>删除</Button>
                        </Popconfirm>:true}
                </div>
            )
        })
        let self = this;
        getAdministrativeArea().then(function (data) {
            if(data.code === 200){
                self.setState({data: data.data, showData: data.data[0].children[0].children[0].children, loading: false})
            }
        })
    }

    getData = () => {
        let self = this;
        self.setState({loading: true});
        getSubAdministrativeAreaId(this.state.regionId).then(function (data) {
            if(data.code === 200){
                self.setState({showData: data.data, loading: false})
            }
        })
    }

    del = (id)=> {
        let self = this;
        delAdministrativeArea(id).then(function (data) {
            if(JSON.parse(data).code === 200){
                self.getData();
                message.success("删除成功");
            }else{
                message.error(data.msg)
            }
        })
    }

    mod = ()=> {

    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            this.setState({
                reservoirName: values.reservoirName
            }, () => {
                this.getData();
            })
        })

    }


    onChange = (value) => {

        this.setState({
            regionId: value[value.length-1]
        }, () => {
            this.getData();
        })

    }

    render(){
        let data = [];
        for(let i in this.state.showData){
            data.push({
                key: i,
                id: this.state.showData[i].id,
                regionname: this.state.showData[i].regionname,
                regioncode: this.state.showData[i].regioncode,
                plevel: this.state.showData[i].plevel,
                status: this.state.showData[i].status,
                orderby: this.state.showData[i].orderby
            })
        }

        return(
            <div className="clearfix">
                <div className="clearfix tableFilter">
                    <Cascader options={this.state.data} className="fl" defaultValue={[4, 20, 21]} style={{width: '330px'}} placeholder='请选择地区' onChange={this.onChange} changeOnSelect />
                    {this.state.permissions["sys:administrativeArea:add"]?<AddAdministrativeDivisionForm retrieve={this.getData} id={this.state.regionId} />:true}
                </div>
                <Table className="mt10 scrollTable" columns={columns} pagination={this.state.pagination} dataSource={data} loading={this.state.loading} onChange={this.handleTableChange} scroll={{y: this.state.height }} bordered />
            </div>
        )
    }

}

class SysSettings extends React.Component{

    onChange = () => {

    }

    render(){
        return(
            <div className="mt10 page">
                <Tabs defaultActiveKey="1" onChange={this.onChange}>
                    <TabPane tab="平台设置" key="1">Content of Tab Pane 1</TabPane>
                    <TabPane tab="行政区划设置" key="2"><AdministrativeDivision /></TabPane>
                    <TabPane tab="职能部门设置" key="3">Content of Tab Pane 3</TabPane>
                    <TabPane tab="养护公司及人员设置" key="4">Content of Tab Pane 3</TabPane>
                    <TabPane tab="问题分类设置" key="5">Content of Tab Pane 3</TabPane>
                    <TabPane tab="数据备份设置" key="6">Content of Tab Pane 3</TabPane>
                    <TabPane tab="安全设置" key="7">Content of Tab Pane 3</TabPane>
                </Tabs>
            </div>
        )
    }


}

export default SysSettings;

